package com.service;

import cn.hutool.core.util.RandomUtil;
import com.service.IMailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.BoundZSetOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service
public class MailServiceImpl implements IMailService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;

    @Override
    public void sendMail(String mail) {

        //产生验证码，并保存到redis
        String code= RandomUtil.randomString(4);
        redisTemplate.boundZSetOps("mail").add(mail+":"+code,System.currentTimeMillis());  //currentTimeMillis是当前时间
        //发送
        SimpleMailMessage message=new SimpleMailMessage();
        message.setFrom(from); //发送者
        message.setTo(mail);  //接收者
        message.setSubject("验证码注册");
        message.setText("您的验证码是："+code);
        javaMailSender.send(message);

    }

    @Override
    public boolean checkCode(String mail, String code) {

        //从redis 取出验证码
        BoundZSetOperations zset=redisTemplate.boundZSetOps("mail");
       Long mingci=redisTemplate.boundZSetOps("mail").rank(mail+":"+code);
       boolean f=mingci!=null;
       if (f){
           //成功要删除原来的
        zset.removeRange(mingci,mingci);
       }

        return f;
    }
}
